/*
 * @Author: hanxin 
 * @Date: 2021-08-14 16:25:55 
 * @Last Modified by: hanxin
 * @Last Modified time: 2021-08-15 00:25:27
 * 服务器推送消息线程
 */
package ServerService;

import common.Message;
import common.MessageType;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.Iterator;

public class serverSendMessagetoAll extends Thread {
    @Override
    public void run() {
        while (true) {
            System.out.println("\n退出消息推送服务请输入exit,关闭服务端输入shutdownserver,关闭注册服务输入shutdownRes");
            System.out.print("send_news_to_all:");
            String news = utility.readString(100);

            if ("exit".equals(news)) {
                System.out.println("\n退出消息推送服务,服务器继续运行..");
                break;
            }
            if ("shutdownserver".equals(news)) {

                System.out.println("真的要关闭服务器吗？y/n");
                String flag = utility.readString(1);

                if (flag.equals("y")) {
                    manageClientThreads.hashtable.clear();
                    System.exit(0);
                }
            }
            if ("shutdownRes".equals(news)) {
                registerSer.loop = false;
            }

            Message mess = new Message();
            mess.setMessType(MessageType.MESSAGE_COMM_MES_TOALL);
            mess.setSender("server");
            mess.setContent("server_to_all: " + news);
            mess.setSendTime(new Date().toString());

            try {
                Iterator<String> iterator = manageClientThreads.hashtable.keySet().iterator();
                while (iterator.hasNext()) {
                    String user = iterator.next().toString();
                    ObjectOutputStream oos = new ObjectOutputStream(
                            manageClientThreads.returnthread(user).socket.getOutputStream());
                    oos.writeObject(mess);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
